import requests
from fake_useragent import UserAgent
from bs4 import BeautifulSoup
import re

url="https://github.com/clash-verge-rev/clash-verge-rev/releases"
headers = {
    "User-Agent": UserAgent().random,
    "Referer": "https://github.com/clash-verge-rev/clash-verge-rev/releases",  # 设置防盗链
}
html=requests.get(url=url,headers=headers)
soup = BeautifulSoup(html.content, 'html.parser')
h2_tags = soup.find_all('h2', {'class': 'sr-only', 'id': True})
print("Clash最新版本："+h2_tags[1].text[16:])
url1="https://github.com/clash-verge-rev/clash-verge-rev/releases/expanded_assets/{}".format(h2_tags[1].text[16:])
print("最新下载地址："+url1)

html1=requests.get(url=url1,headers=headers)
if html1.status_code == 200:
    # print("连接成功...\n" + html.text)
    with open(f'Clash.txt',mode="wb")as f:
        f.write(html1.content)
else:
    print(f"连接失败，状态码: {html.status_code}")

urls1=re.findall(r'<a href="(.*?)" rel',html1.text)
# print(len(urls1))
# print(urls1)
urlsl=[]
for i in urls1:
    if "x64-setup.exe" in i:
        print("64位正常安装版本（推荐）："+f"https://github.com/{i}")
        urlsl.append(f"https://github.com/{i}")
    elif "x64_portable.zip" in i:
        print("64位便携版本（不推荐，无法自动更新）："+f"https://github.com/{i}")
        urlsl.append(f"https://github.com/{i}")
# print(urlsl)
x = int(input("下载最新安装包版本请输入 0\n下载最新便携版本请输入 1\n不下载请输入其他数字（2 或其他非 0 或 1）\n你的输入是："))


def download_file(ur, filename, html2):
    try:
        total_size = int(html2.headers.get('content-length', 0))
        chunk_size = 1024  # 每次下载的块大小，可以根据需要调整
        downloaded_size = 0

        with open(f"D:/360安全浏览器下载/{filename}", 'wb') as f:
            for chunk in html2.iter_content(chunk_size=chunk_size):
                if chunk:
                    f.write(chunk)
                    downloaded_size += len(chunk)
                    progress = (downloaded_size / total_size) * 100
                    print(f"\r下载进度：{progress:.2f}% 完成", end='', flush=True)

        print(f"\n文件从 {ur} 下载成功到 D:/360安全浏览器下载/{filename}")
    except Exception as e:
        print(f"下载 {ur} 失败：{e}")

try:
    if x == 0 or x == 1:
        html2 = requests.get(url=urlsl[x])
        # print(html2.status_code)
        if html2.status_code == 200:
            if x == 0:
                ur = urlsl[0]
                filename = f"Clash {h2_tags[1].text[16:]}安装包版本.exe"
            elif x == 1:
                ur = urlsl[1]
                filename = f"Clash {h2_tags[1].text[16:]}便携版本.7z"
            
            # 调用下载函数
            download_file(ur, filename, html2) # type: ignore
        else:
            print(f"下载 {urlsl[x]} 失败：请求状态码 {html2.status_code}")
    else:
        print("已取消下载，输入不在可选范围内。")
except ValueError:
    print("输入无效，请输入一个数字。")
except Exception as e:
    print(f"下载失败：{e}")
